// 绘制canvas图，并上传
export function drawPhoto(imgUrl, imgInfo, textArr, callback) {
  const canvas = document.createElement('canvas')
  canvas.width = imgInfo.width
  canvas.height = imgInfo.height
  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.src = imgUrl + '?' + new Date().getTime()
  img.setAttribute('crossOrigin', 'anonymous')
  img.onload = () => {
    ctx.drawImage(img, 0, 0, imgInfo.width, imgInfo.height)
    ctx.font = '18px arial'
    for (const i in textArr) {
      ctx.fillText(textArr[i].text, textArr[i].x, textArr[i].y)
    }
    const image = canvas.toDataURL('image/jpeg', 0.7)
    // console.log(image)
    const imgNew = Base64toFile(image, `${Date.now()}.jpg`)
    uploadImage(imgNew, callback)
  }
}

// 将bases64转Blob
export function dataURItoBlob(base64) {
  // console.log(base64Data)
  var type = base64.split(',')[0].match(/:(.*?);/)[1]// 提取base64头的type如 'image/png'
  var bytes = window.atob(base64.split(',')[1])// 去掉url的头，并转换为byte (atob:编码 btoa:解码)

  // 处理异常,将ascii码小于0的转换为大于0
  var ab = new ArrayBuffer(bytes.length)// 通用的、固定长度(bytes.length)的原始二进制数据缓冲区对象
  var ia = new Uint8Array(ab)
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type: type })
}

// 将base64转换为文件
export function Base64toFile(dataurl, filename) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
// 图片上传
export function uploadImage(f, callback) {
  var xhr = new XMLHttpRequest()
  var formData = new FormData()
  console.log(f)
  formData.append('file', f)
  xhr.onreadystatechange = function(e) {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText)
        callback(xhr.responseText)
      } else {
        console.log(xhr.responseText)
      }
    }
  }

  xhr.open('POST', 'https://fw.tfnhg.com/oss_upload', true)
  xhr.send(formData)
}

//  将图片转为base64
export function imgToBase64(imgUrl, imgInfo) {
  const canvas = document.createElement('canvas')
  canvas.width = imgInfo.width
  canvas.height = imgInfo.height
  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.src = imgUrl + '?' + new Date().getTime()
  img.setAttribute('crossOrigin', 'anonymous')
  img.onload = () => {
    ctx.drawImage(img, 0, 0, imgInfo.width, imgInfo.height)
    const image = canvas.toDataURL('image/jpeg', 0.7)
    console.log(image)
  }
}
